package com.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srb.core.listener.ExcelDictDTOListener;
import com.srb.core.mapper.DictMapper;
import com.srb.core.pojo.dto.ExcelDictDTO;
import com.srb.core.pojo.entity.Dict;
import com.srb.core.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author dapeng
 * @since 2021-08-08
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private ExcelDictDTOListener listener;

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, listener)
//                .excelType(ExcelTypeEnum.XLSX)
                .sheet().doRead();
        log.info("excel导入成功!");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> list = baseMapper.selectList(null);
        List<ExcelDictDTO> dtoList = new ArrayList<>(list.size());
        if (CollectionUtils.isEmpty(list)) {
            return dtoList;
        }
        for (Dict dict : list) {
            ExcelDictDTO dto = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, dto);
            dtoList.add(dto);
        }
        return dtoList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        try {
            List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (!CollectionUtils.isEmpty(dictList)){
                log.info("redis查询数据...");
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis查询数据异常", ExceptionUtils.getStackTrace(e));
        }

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<Dict> list = baseMapper.selectList(wrapper);
        //填充hasChildren字段
        list.forEach(dict -> {
            //判断当前节点是否有子节点
            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        });
        try {
            //存redis,5分钟失效
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId,list,5, TimeUnit.MINUTES);
            log.info("redis存储数据...");
        } catch (Exception e) {
            log.error("redis存储数据异常", ExceptionUtils.getStackTrace(e));
        }
        return list;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        if (null == dict){
            return Collections.EMPTY_LIST;
        }
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDicCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict parentDict = baseMapper.selectOne(queryWrapper);
        if (parentDict == null){
            return "";
        }
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentDict.getId())
                .eq("value",value);
        Dict dict = baseMapper.selectOne(queryWrapper);
        if (null == dict){
            return "";
        }
        return dict.getName();
    }

    /**
     * 判断当前id所在的节点是否有子节点
     *
     * @param id
     * @return
     */
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0 ? true : false;
    }
}
